package com.cskaoyan.util;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.exception.CustomValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * @author stone
 * @date 2022/01/03 17:48
 */
public class ValidationUtil {

    public static BaseRespVo validateResult(BindingResult bindingResult) {
        //如果校验没有通过是谁导致的 → 获得校验错误
        FieldError fieldError = bindingResult.getFieldError();
        //校验没有通过我们能获得哪些信息
        String field = fieldError.getField();//获得成员变量名 → 请求参数名
        Object rejectedValue = fieldError.getRejectedValue();//导致校验失败的值
        String defaultMessage = fieldError.getDefaultMessage();
        String msg = "请求参数" + field + "没有通过校验：" + rejectedValue + "; " + defaultMessage;
        return BaseRespVo.fail(msg);
    }

    public static void validate2(BindingResult bindingResult) throws CustomValidationException {
        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            //校验没有通过我们能获得哪些信息
            String field = fieldError.getField();//获得成员变量名 → 请求参数名
            Object rejectedValue = fieldError.getRejectedValue();//导致校验失败的值
            String defaultMessage = fieldError.getDefaultMessage();
            String msg = "请求参数" + field + "没有通过校验：" + rejectedValue + "; " + defaultMessage;
            //抛出异常
            throw new CustomValidationException(msg);
            //异常处理
        }

    }
}
